package com.atguigu.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author lhh
 * @ClassName WebSecurityConfig
 * @date 2022/9/29 19:11
 */

@Configuration
@EnableWebSecurity  //@EnableWebSecurity是开启SpringSecurity的默认行为
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /*@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("lucy")
                .password(new BCryptPasswordEncoder().encode("123456"))
                .roles("");

    }*/

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //必须调用父类的方法，否则就不需要认证即可访问
        //super.configure(http);
        //允许iframe嵌套显示
        http.headers().frameOptions().disable();
        //允许iframe显示
        //http.headers().frameOptions().sameOrigin();
        //登录设置
        http
                .authorizeRequests()
                //允许匿名用户访问的路径
                .antMatchers("/static/**","/loginPage").permitAll()
                // 其它页面全部需要验证
                .anyRequest().authenticated();
        //登录配置
        http
                .formLogin()
                //表单页面的地址
                .loginPage("/loginPage")
                //提交表单的处理地址
                .loginProcessingUrl("/login")
                //登录成功后哪里
                .defaultSuccessUrl("/");
        //退出设置
        http
                .logout()
                //退出登陆的路径，指定spring security拦截的注销url,退出功能是security提供的
                .logoutUrl("/logout")
                .invalidateHttpSession(true)
                //用户退出后要被重定向的url
                .logoutSuccessUrl("/loginPage");
        //取消csrf
        http
                //关闭跨域请求伪造功能
                .csrf().disable();

        //添加自定义无权限处理器
        http.exceptionHandling().accessDeniedHandler(new CustomAccessDeineHandler());

    }

}
